<template>
  <div class="dashboard-wrapper">
    <div class="dashboard-container">
      <!-- 顶部导航栏 -->
      <div class="dashboard-header">
        <div class="header-left">
          <h1>管理员控制台</h1>
        </div>
        <div class="header-right">
          <div class="user-info" @click="toggleUserMenu">
            <div class="user-avatar">
              {{ user.username?.charAt(0).toUpperCase() || 'A' }}
            </div>
            <span class="username">{{ user.username }}</span>
            <i class="fas fa-chevron-down"></i>
          </div>
          
          <!-- 用户菜单 -->
          <div v-if="userMenuVisible" class="user-menu">
            <div class="menu-item" @click="manageProfile">
              <i class="fas fa-user"></i>
              <span>个人资料</span>
            </div>
            <div class="menu-item" @click="handleLogout">
              <i class="fas fa-sign-out-alt"></i>
              <span>退出登录</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="welcome-section">
        <h2>欢迎回来，管理员 {{ user.username }}！</h2>
        <p>今天是 {{ getCurrentDate() }}，让我们一起管理平台吧！</p>
      </div>
      
      <div class="dashboard-stats">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="fas fa-users"></i>
          </div>
          <div class="stat-info">
            <h3>用户总数</h3>
            <p class="stat-number">{{ stats.userCount || 0 }}</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <i class="fas fa-tasks"></i>
          </div>
          <div class="stat-info">
            <h3>任务总数</h3>
            <p class="stat-number">{{ stats.taskCount || 0 }}</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <i class="fas fa-wallet"></i>
          </div>
          <div class="stat-info">
            <h3>交易总额</h3>
            <p class="stat-number">¥{{ stats.totalAmount || 0 }}</p>
          </div>
        </div>
      </div>
      
      <div class="dashboard-content">
        <div class="content-section">
          <h2>系统管理</h2>
          <div class="management-actions">
            <button @click="manageUsers" class="action-button primary">
              <i class="fas fa-users"></i>
              <span>用户管理</span>
            </button>
            <button @click="manageTasks" class="action-button secondary">
              <i class="fas fa-tasks"></i>
              <span>任务管理</span>
            </button>
            <button @click="manageTaskEvaluations" class="action-button accent">
              <i class="fas fa-star"></i>
              <span>任务评价管理</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../api/index.js'

const router = useRouter()
const user = ref({})
const stats = ref({
  userCount: 0,
  taskCount: 0,
  totalAmount: 0
})
const userMenuVisible = ref(false)

// 获取当前用户信息
const fetchCurrentUser = async () => {
  try {
    console.log('开始获取当前管理员信息')
    const response = await api.get('/user/current')
    console.log('获取管理员信息响应:', response)
    if (response.code === 0) {
      user.value = response.data
      console.log('管理员信息获取成功:', user.value)
    } else {
      // 用户未登录，跳转到登录页
      console.log('管理员未登录，跳转到登录页')
      // 先清除本地存储
      localStorage.removeItem('user')
      router.push('/login')
    }
  } catch (error) {
    console.error('获取管理员信息失败:', error)
    // 先清除本地存储
    localStorage.removeItem('user')
    router.push('/login')
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await api.get('/stats/summary')
    if (response.code === 0) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 切换用户菜单显示
const toggleUserMenu = () => {
  userMenuVisible.value = !userMenuVisible.value
}

// 点击其他地方隐藏菜单
const handleClickOutside = (event) => {
  if (userMenuVisible.value && !event.target.closest('.user-info')) {
    userMenuVisible.value = false
  }
}

// 用户登出
const handleLogout = async () => {
  userMenuVisible.value = false
  try {
    const response = await api.post('/user/logout')
    if (response.code === 0) {
      // 清除本地存储的用户信息
      localStorage.removeItem('user')
      router.push('/login')
    } else {
      alert('登出失败')
    }
  } catch (error) {
    console.error('登出失败:', error)
    alert('登出失败，请重试')
  }
}

// 管理用户
const manageUsers = () => {
  router.push('/users')
}

// 管理任务
const manageTasks = () => {
  router.push('/task-management')
}

// 管理任务评价
const manageTaskEvaluations = () => {
  router.push('/task-evaluation-management')
}

// 管理个人信息
const manageProfile = () => {
  router.push('/profile')
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

// 获取当前日期
const getCurrentDate = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const weekday = weekdays[date.getDay()]
  return `${year}年${month}月${day}日 ${weekday}`
}

onMounted(() => {
  fetchCurrentUser()
  fetchStats()
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.dashboard-wrapper {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
}

.dashboard-container {
  width: 100%;
  max-width: none;
  min-height: calc(100vh - 40px);
  background: white;
  border-radius: 12px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  padding: 0;
  margin: 0 auto;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}

/* 顶部导航栏 */
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #eee;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.dashboard-header h1 {
  font-size: 28px;
  font-weight: 700;
  margin: 0;
}

.header-right {
  position: relative;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 20px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 10px;
}

.username {
  margin-right: 8px;
  font-weight: 500;
}

.user-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  width: 200px;
  z-index: 100;
  margin-top: 10px;
  overflow: hidden;
  animation: slideDown 0.3s ease;
  border: 1px solid #eee;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  color: #333;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #667eea;
  color: white;
}

.menu-item:first-child {
  border-bottom: 1px solid #eee;
}

.menu-item i {
  margin-right: 10px;
  width: 20px;
  text-align: center;
}

.welcome-section {
  padding: 30px;
  text-align: center;
  background: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
}

.welcome-section h2 {
  color: #333;
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: 700;
}

.welcome-section p {
  color: #666;
  font-size: 18px;
  margin: 0;
}

.dashboard-stats {
  display: flex;
  gap: 25px;
  margin-bottom: 40px;
  flex-wrap: wrap;
  padding: 0 30px;
  justify-content: center;
}

.stat-card {
  flex: 1;
  min-width: 250px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 25px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s, box-shadow 0.3s;
  color: white;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: 0.5s;
}

.stat-card:hover::before {
  left: 100%;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  margin-right: 20px;
  flex-shrink: 0;
}

.stat-info h3 {
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 8px;
  font-size: 18px;
  font-weight: 600;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: white;
  margin: 0;
}

.dashboard-content {
  display: flex;
  gap: 35px;
  margin-bottom: 40px;
  flex-wrap: wrap;
  padding: 0 30px;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 30px;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
}

.content-section {
  flex: 1;
  min-width: 350px;
}

.content-section h2 {
  color: #333;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 3px solid #667eea;
  font-size: 24px;
  font-weight: 600;
  text-align: center;
  position: relative;
}

.content-section h2::after {
  content: '';
  position: absolute;
  bottom: -3px;
  left: 50%;
  transform: translateX(-50%);
  width: 50px;
  height: 3px;
  background: linear-gradient(90deg, #667eea, #764ba2);
  border-radius: 3px;
}

.management-actions {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 20px;
}

.action-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 25px 15px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 600;
  font-size: 16px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  min-height: 120px;
  background: white;
  color: #333;
  border: 1px solid #eee;
  position: relative;
  overflow: hidden;
}

.action-button:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
  border-color: #667eea;
}

.action-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: 0.5s;
}

.action-button:hover::before {
  left: 100%;
}

.action-button i {
  font-size: 32px;
  margin-bottom: 12px;
  color: #667eea;
}

.action-button.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.action-button.primary i {
  color: white;
}

.action-button.secondary {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.action-button.secondary i {
  color: white;
}

.action-button.secondary:hover {
  background: linear-gradient(135deg, #3a9cea 0%, #00d2fe 100%);
}

.action-button.accent {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.action-button.accent i {
  color: white;
}

.action-button.accent:hover {
  background: linear-gradient(135deg, #32d86d 0%, #27e8c7 100%);
}

.action-button.info {
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  color: white;
}

.action-button.info i {
  color: white;
}

.action-button.info:hover {
  background: linear-gradient(135deg, #ff8a8e 0%, #f9c0c4 100%);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .header-left, .header-right {
    width: 100%;
    text-align: center;
  }
  
  .user-menu {
    right: auto;
    left: 50%;
    transform: translateX(-50%);
  }
  
  .dashboard-content {
    flex-direction: column;
  }
  
  .content-section {
    min-width: 100%;
  }
  
  .dashboard-stats {
    flex-direction: column;
  }
  
  .tasks-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 1200px) {
  .dashboard-container {
    padding: 25px;
  }
  
  .dashboard-stats {
    gap: 20px;
  }
  
  .stat-card {
    padding: 20px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
    margin-right: 15px;
  }
}
</style>